﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace iMoreThanReader
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
        }

        private void ZapScroller_GotFocus(object sender, RoutedEventArgs e)
        {

        }

        private void button1_Click_1(object sender, RoutedEventArgs e)
        {
            //button1.Content = zap.Items[zap.CurrentItemIndex].ToString();
            //label1.Content = zap.CurrentItemIndex;
            Speech(zap.Items[zap.CurrentItemIndex].ToString());
        }


        WMPLib.IWMPPlaylist pl;
        WMPLib.IWMPPlaylistArray plItems;
        static string gSpeechURL = "http://translate.google.com/translate_tts?tl=en&q=";
        WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();

        public void Speech(string text)
        {
            //text = text.Substring(0, 99);
            if (text.Length < 100)
            {
                string url = gSpeechURL + text.Replace(" ", "+");
                TextToSpeech(url);
            }
            else
            {
                string[] texts = text.Split(new char[] { '.', ',' }, 99);
                CreatePlayList();
                foreach (var t in texts)
                {
                    string url = gSpeechURL + t.Trim().Replace(" ", "+");
                    AddMediaToPlayList(url);
                    TextToSpeechPlaylist();                    
                }
            }
        }

        private void CreatePlayList() 
        {
            pl = wplayer.playlistCollection.newPlaylist("en");
        }

        private void AddMediaToPlayList(string url)
        {
            pl.appendItem(wplayer.newMedia(url));        
        }



        private void TextToSpeechPlaylist()
        {
            wplayer.currentPlaylist = pl;
            wplayer.controls.play();
            wplayer.playlistCollection.remove(pl);
        }

        private void TextToSpeech(string url)
        {                
            wplayer.URL = url;
            wplayer.controls.play();

        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
        }
    }
}
